package com.chuangfeng.framework.core.common.util;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 处理JSON字符串工具类
 * @author xiedy
 *
 */
public class JsonUtil {

	public static void main(String[] args) {
		List<String> list = new ArrayList<String>();
		list.add("111");
		list.add("111");
		list.add("111");
		System.out.println(toJSON(list).toString());
		printJSON(list);
		System.out.println(toJSONString(list));
		JSONObject jo = new JSONObject();
		jo.put("name", "xiedy");
		jo.put("sex","male");
		jo.put("age", "1");
		JSONArray ja = new JSONArray();
		ja.add(jo);
		ja.add(jo);
		JSONObject jo2 = new JSONObject();
		jo2.put("id", "1");
		jo2.put("content",ja);
		printJSON(jo2);
		
	}
	
	public static void printJSON(Object obj){
		System.out.println("===json====");
		Object json = toJSON(obj);
		if(json instanceof JSONArray){
			System.out.println(((JSONArray)json).toString(4));
		}else if(json instanceof JSONObject){
			System.out.println(((JSONObject)json).toString(4));
		}else{
			if(json == null){
				System.out.println("null");
			}else{
				System.out.println(json.toString());
			}
		}
		System.out.println("===json====");
	}
	
	public static Object toJSON(Object obj){
		Object tmp = null;
		//基本数据类型则直接返回
		if(isBasicType(obj)){
			return obj;
		}
		if((obj instanceof List) || (obj.getClass().isArray())){
			JSONArray ja = JSONArray.fromObject(obj);
			tmp = ja;
		}else{
			JSONObject jobject = JSONObject.fromObject(obj);
			tmp = jobject;
		}
		return tmp;
	}
	
	private static boolean isBasicType(Object obj){
		if(obj == null){
			return true;
		}
		//字符串
		if((obj instanceof String) || (obj instanceof Character)){
			return true;
		}
		//数字
		if(obj instanceof Number){
			return true;
		}
		if(obj instanceof Boolean){
			return true;
		}
		return false;
	}
	
	public static String toJSONString(Object obj){
		Object json = toJSON(obj);
		if(json == null){
			return "null";
		}else{
			return json.toString();
		}
	}
}

